/**
 * Created by xiey on 2016/3/16.
 */
as.directive('numberField', [function () {
    return {
        restrict: 'EA',
        scope   : {},
        require : {
            ngModel: '^^ngModel',
            field  : '^^aField'
        },
        template: '<input type="number" max="{{max}}" min="{{min}}" class="form-control input-sm" placeholder="{{::placeholder}}">',
        replace : true,
        link    : function (scope, el, attr, req) {
            var fieldCfg = req.field.getFieldCfg(), message = fieldCfg.message;
            scope.ngModel = req.ngModel;
            scope.placeholder = fieldCfg.placeholder || ('请输入' + fieldCfg.label);
            el.on('input', function () {
                req.ngModel.$setViewValue(el.val());
            });
            if (message.min) {
                req.ngModel.$validators.min = function (modelValue, viewValue) {
                    var value = modelValue || viewValue;
                    if (value === undefined || value === '') {
                        return true;
                    }
                    return value >= message.min.value;
                };
            }
            if (message.max) {
                req.ngModel.$validators.max = function (modelValue, viewValue) {
                    var value = modelValue || viewValue;
                    if (value === undefined || value === '') {
                        return true;
                    }
                    return value <= message.max.value;
                };
            }
            req.ngModel.$render = function () {
                el.val(req.ngModel.$modelValue || req.ngModel.$viewValue);
            };
        }
    };
}]);